package com.lagou.rpc.handler;

import com.lagou.request.RpcRequest;
import com.lagou.rpc.util.SpringConfigUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义业务处理器handler
 *
 * @author thresh
 * @date 2021/2/22 20:13
 */
public class UserServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 客户端读取数据时，调用该方法
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 获取RpcRequest对象
        RpcRequest req = (RpcRequest) msg;

        // 通过反射获取字节码，从容器中获取对象
        Class<?> aClass = Class.forName(req.getClassName());
        Object bean  = SpringConfigUtils.getBean(aClass);

        // 根据方法名获取方法，并调用对应的方法
        Method method = aClass.getMethod(req.getMethodName(), req.getParameterTypes());
        Object result = method.invoke(bean, req.getParameters());

        // 把执行结果写回客户端
        ctx.writeAndFlush(result);

    }
}
